#!/usr/bin/env python3
# vim: tabstop=4 shiftwidth=4 expandtab

import argparse
import sys
import sparty

def main():
    parser = argparse.ArgumentParser(description="Python module/CLI program for making network requests with the spartan protocol.")
    parser.add_argument("-u","--url",help="Fully qualified URL to fetch.")
    parser.add_argument("-o","--outputfile",help="File to output response body to.")
    parser.add_argument("-q","--quiet",help="Don't print response header.",action="store_true")
    parser.add_argument("-n","--nobody",help="Only print response header.",action="store_true")
    parser.add_argument("-m","--message",help="A string message to send with the request.",default="")
    parser.add_argument("-i","--inputfile",help="A file to send with the request. Overrides -m/--message. This can in turn be overriden by a QUERY STRING in the supplied URL, which will be sent as a message instead.")
    args = parser.parse_args()

    if not args.url:
        parser.print_help()
    else:
        if args.inputfile:
            with open(args.inputfile, "rb") as f: message = f.read()
        else:
            message = str.encode(args.message)
        responseobj = sparty.request(url = args.url, message = message)

        if not args.quiet:
            print(f"{str(responseobj.responsecode)} {str(responseobj.meta)}", file=sys.stderr)

        outputfile = open(args.outputfile, "wb") if args.outputfile else sys.stdout.buffer

        while not args.nobody:
            buf = responseobj.read()
            if len(buf) == 0:
                break
            else:
                outputfile.write(buf)

        responseobj.discard()

if __name__ == "__main__":

    main()

